﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using thinger.CommunicationLib;
using thinger.VisionModels;
using thinger.VisitionDAL;

namespace thinger.VisionDemo
{
    public partial class FrmAURecipe : Form
    {
        #region 初始化文件
        public RecipeEntity recipeEntity { get; set; }
        private DataProcessing dataProcessing = new DataProcessing();
        private ZmotionEx zmotion = new ZmotionEx();
        private SerialPortSet serialPortSet = new SerialPortSet();
        private SysConfig sysConfig = new SysConfig();
        ModbusRTU device = new ModbusRTU();
        /// <summary>
        /// 创建委托变量
        /// </summary>
        public ReceiveDelegate ChildReceive { get; set; }
        public FrmAURecipe(ZmotionEx zmotion,ModbusRTU device,SerialPortSet serialPortSet)
        {
            this.zmotion = zmotion;
            InitializeComponent();
            this.device = device;
            this.serialPortSet = serialPortSet;
        }
        private void FrmAURecipe_Load(object sender, EventArgs e)
        {
            num_Index.Value = recipeEntity.Index;
            txt_ProductName.Text = recipeEntity.ProductName;
            num_ProPhotoU1Pos.Value = (decimal)recipeEntity.ProPhotoU1Pos;
            num_ProPhotoZ1Pos.Value = (decimal)recipeEntity.ProPhotoZ1Pos;

            num_ProPhotoU2Pos.Value = (decimal)recipeEntity.ProPhotoU2Pos;
            num_ProPhotoZ2Pos.Value = (decimal)recipeEntity.ProPhotoZ2Pos;
            num_ProScrewLU1Pos.Value = (decimal)recipeEntity.ProScrewLU1Pos;
            nume_ProScrewLZ1Pos.Value = (decimal)recipeEntity.ProScrewLZ1Pos;

            num_ProScrewLU1Pos2.Value = (decimal)recipeEntity.ProScrewLU1Pos2;
            num_ProScrewLZ1Pos2.Value = (decimal)recipeEntity.ProScrewLZ1Pos2;

            num_ProScrewRU2Pos.Value = (decimal)recipeEntity.ProScrewRU2Pos1;
            num_ProScrewRZ2Pos.Value = (decimal)recipeEntity.ProScrewRZ2Pos1;

            num_ProPutInXPox.Value = (decimal)recipeEntity.ProPutInXPox;
            num_ProPutInYPos.Value = (decimal)recipeEntity.ProPutInYPox;

            num_ProScrewXPos.Value = (decimal)recipeEntity.ProScrewXPos;
            num_ProScrewYPos.Value = (decimal)recipeEntity.ProScrewYPos;

            list_Status.Text = recipeEntity.Status;

            this.updateTimer.Interval = 1000;
            this.updateTimer.Tick += UpdateTimer_Tick;
            this.updateTimer.Start();
        }
        #endregion

        #region
        private void btn_Read_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btn_Save_Click(object sender, EventArgs e)
        {
            recipeEntity.Index = (int)num_Index.Value;
            recipeEntity.ProductName = txt_ProductName.Text;
            recipeEntity.ProPhotoU1Pos = (double)num_ProPhotoU1Pos.Value;
            recipeEntity.ProPhotoZ1Pos = (double)num_ProPhotoZ1Pos.Value;

            recipeEntity.ProPhotoU2Pos = (double)num_ProPhotoU2Pos.Value;
            recipeEntity.ProPhotoZ2Pos = (double)num_ProPhotoZ2Pos.Value;
            recipeEntity.ProScrewLU1Pos = (double)num_ProScrewLU1Pos.Value;
            recipeEntity.ProScrewLZ1Pos = (double)nume_ProScrewLZ1Pos.Value;

            recipeEntity.ProScrewLU1Pos2 = (double)num_ProScrewLU1Pos2.Value;
            recipeEntity.ProScrewLZ1Pos2 = (double)num_ProScrewLZ1Pos2.Value;

            recipeEntity.ProScrewRU2Pos1 = (double)num_ProScrewRU2Pos.Value;
            recipeEntity.ProScrewRZ2Pos1 = (double)num_ProScrewRZ2Pos.Value;

            recipeEntity.ProPutInXPox = (double)num_ProPutInXPox.Value;
            recipeEntity.ProPutInYPox = (double)num_ProPutInYPos.Value;

            recipeEntity.ProScrewXPos = (double)num_ProScrewXPos.Value;
            recipeEntity.ProScrewYPos = (double)num_ProScrewYPos.Value;
            recipeEntity.Status = list_Status.Text;

            //修改变变量
            ChildReceive(recipeEntity);
            this.Close();

        }
        #endregion

        #region 点击点动控制
        private void Common_MouseDown(object sender, MouseEventArgs e)
        {
            if (sender is Button button)
            {
                bool resut = GetAxisNoAndDir(button, out short axisNo, out bool dir);

                if (resut)
                {
                    float vel = GetVelByAxisNo(axisNo);
                    zmotion.VMove(axisNo, vel, dir, 0.0f, vel * 10, vel * 10, 100);
                }
                else
                {
                    MessageBox.Show("请检查按钮参数绑定是否正确", "参数错误");
                }
            }
        }

        private bool GetAxisNoAndDir(Button button, out short axisNo, out bool dir)
        {
            if (button.Tag != null && button.Tag.ToString().Length > 0)
            {
                string tag = button.Tag.ToString();

                if (tag.Contains(","))
                {
                    string[] values = tag.Split(',');

                    axisNo = Convert.ToInt16(values[0]);

                    dir = values[1] == "1";

                    return true;

                }
            }

            axisNo = 0;
            dir = false;
            return false;
        }
        private float GetVelByAxisNo(int axisNo)
        {
            switch (axisNo)
            {

                default: return 1000.0f;
            }
        }

        private void Common_MouseUp(object sender, MouseEventArgs e)
        {
            if (sender is Button button)
            {
                bool resut = GetAxisNoAndDir(button, out short axisNo, out bool dir);

                if (resut)
                {
                    zmotion.StopAxis(axisNo);
                }
                else
                {
                    MessageBox.Show("请检查按钮参数绑定是否正确", "参数错误");
                }
            }
        }
        //左右螺丝刀旋转控制
        private void btn_ScrewComRun_MouseDown(object sender, MouseEventArgs e)
        {
            if (sender is Button button)
            {
                bool resut = GetAxisNoAndDir(button, out short axisNo, out bool dir);
                if (resut)
                {
                    byte devAddress = 0;
                    string screwTorque = null;
                    //通用性左右螺丝刀选择
                    if (axisNo == 6)
                    {
                        devAddress = device.LDevAddress;
                        if (dir)
                        {
                            screwTorque = serialPortSet.LScrewTorque;
                        }
                        else
                        {
                            screwTorque = (Convert.ToInt16(serialPortSet.LScrewTorque) * -1).ToString();
                        }
                    }
                    else if (axisNo == 7)
                    {
                        devAddress = device.RDevAddress;
                        if (dir)
                        {
                            screwTorque = serialPortSet.RScrewTorque;
                        }
                        else
                        {
                            screwTorque = (Convert.ToInt16(serialPortSet.RScrewTorque) * -1).ToString();
                        }

                    }
                    string writeForwardAdd = "07 03";
                    string str = device.CommonMotorControl(devAddress, 06, writeForwardAdd, screwTorque);
                    CommonMethods.AddLogAddDay(this.lst_Info, 4, "螺丝刀启动成功");
                }
                else
                {
                    MessageBox.Show("请检查按钮参数绑定是否正确", "参数错误");
                }
            }
        }

        private void btn_ScrewComStop_MouseUp(object sender, MouseEventArgs e)
        {
            if (sender is Button button)
            {
                bool resut = GetAxisNoAndDir(button, out short axisNo, out bool dir);
                string setStopTorque = "00";
                if (resut)
                {
                    byte devAddress = 0;
                    //通用性左右螺丝刀选择
                    if (axisNo == 6)
                    {
                        devAddress = device.LDevAddress;
                    }
                    else if (axisNo == 7)
                    {
                        devAddress = device.RDevAddress;

                    }
                    string writeForwardAdd = "07 03";
                    string str = device.CommonMotorControl(devAddress, 06, writeForwardAdd, setStopTorque);
                    CommonMethods.AddLogAddDay(this.lst_Info, 4, "螺丝刀停止");
                }
                else
                {
                    MessageBox.Show("请检查按钮参数绑定是否正确", "参数错误");
                }
            }
        }

        private void btn_ProPhotoLPos_Click(object sender, EventArgs e)
        {
            num_ProPhotoU1Pos.Value = (decimal)dataProcessing.AxisPulTomm((float)Convert.ToDecimal((float)Convert.ToDouble(zmotion.GetU1Pos())), sysConfig.U1mmAngle, sysConfig.U1PulAngle);
            num_ProPhotoZ1Pos.Value = (decimal)dataProcessing.AxisPulTomm((float)Convert.ToDecimal((float)Convert.ToDouble(zmotion.GetZ1Pos())), sysConfig.Z1mmAngle, sysConfig.Z1PulAngle);
        }

        private void btn_ProPhotoRPos_Click(object sender, EventArgs e)
        {
            num_ProPhotoU2Pos.Value = (decimal)dataProcessing.AxisPulTomm((float)Convert.ToDecimal((float)Convert.ToDouble(zmotion.GetU2Pos())), sysConfig.U2mmAngle, sysConfig.U2PulAngle);
            num_ProPhotoZ2Pos.Value = (decimal)dataProcessing.AxisPulTomm((float)Convert.ToDecimal((float)Convert.ToDouble(zmotion.GetZ2Pos())), sysConfig.Z2mmAngle, sysConfig.Z2PulAngle);

        }

        private void btn_ScrewLPos_Click(object sender, EventArgs e)
        {
            num_ProScrewLU1Pos.Value = (decimal)dataProcessing.AxisPulTomm((float)Convert.ToDecimal((float)Convert.ToDouble(zmotion.GetU1Pos())), sysConfig.U1mmAngle, sysConfig.U1PulAngle);
            nume_ProScrewLZ1Pos.Value = (decimal)dataProcessing.AxisPulTomm((float)Convert.ToDecimal((float)Convert.ToDouble(zmotion.GetZ1Pos())), sysConfig.Z1mmAngle, sysConfig.Z1PulAngle);
        }

        private void btn_ScrewLPos2_Click(object sender, EventArgs e)
        {
            num_ProScrewLU1Pos2.Value = (decimal)dataProcessing.AxisPulTomm((float)Convert.ToDecimal((float)Convert.ToDouble(zmotion.GetU1Pos())), sysConfig.U1mmAngle, sysConfig.U1PulAngle);
            num_ProScrewLZ1Pos2.Value = (decimal)dataProcessing.AxisPulTomm((float)Convert.ToDecimal((float)Convert.ToDouble(zmotion.GetZ1Pos())), sysConfig.Z1mmAngle, sysConfig.Z1PulAngle);
        }

        private void btn_ScrewRPos2_Click(object sender, EventArgs e)
        {
            num_ProScrewRU2Pos.Value = (decimal)dataProcessing.AxisPulTomm((float)Convert.ToDecimal((float)Convert.ToDouble(zmotion.GetU2Pos())), sysConfig.U2mmAngle, sysConfig.U2PulAngle);
            num_ProScrewRZ2Pos.Value = (decimal)dataProcessing.AxisPulTomm((float)Convert.ToDecimal((float)Convert.ToDouble(zmotion.GetZ2Pos())), sysConfig.Z2mmAngle, sysConfig.Z2PulAngle);
        }

        private void btn_ProPutIn_Click(object sender, EventArgs e)
        {
            num_ProPutInXPox.Value = (decimal)dataProcessing.AxisPulTomm((float)Convert.ToDecimal((float)Convert.ToDecimal(zmotion.GetXPos())), sysConfig.XmmAngle, sysConfig.XPulAngle);
            num_ProPutInYPos.Value = (decimal)dataProcessing.AxisPulToAngle((float)Convert.ToDecimal((float)Convert.ToDouble(zmotion.GetYPos())), sysConfig.YPulAngle, sysConfig.YmmAngle);
        }

        private void ptn_ProScrew_Click(object sender, EventArgs e)
        {
            num_ProScrewXPos.Value = (decimal)dataProcessing.AxisPulTomm((float)Convert.ToDecimal((float)Convert.ToDecimal(zmotion.GetXPos())), sysConfig.XmmAngle, sysConfig.XPulAngle);
            num_ProScrewYPos.Value = (decimal)dataProcessing.AxisPulToAngle((float)Convert.ToDecimal((float)Convert.ToDouble(zmotion.GetYPos())), sysConfig.YPulAngle, sysConfig.YmmAngle);
        }

        #endregion


        #region IO控制   和电机手动操作控制
        //左刀头下降
        private void btn_ScrewLDownOut_Click(object sender, EventArgs e)
        {
            if (zmotion.connectedOK)
            {
                bool setValue = this.btn_ScrewLDownOut.BackColor != Color.Green;

                if (setValue)
                {
                    zmotion.ScrewLDownOutOpen();
                }
                else
                {
                    zmotion.ScrewLDownOutClose();
                }
            }
            else
            {
                AddLog(1, "请检查通信是否连接正常");
            }
        }

        //右刀头下降
        private void btn_ScrewRDownOut_Click(object sender, EventArgs e)
        {
            if (zmotion.connectedOK)
            {
                bool setValue = this.btn_ScrewRDownOut.BackColor != Color.Green;

                if (setValue)
                {
                    zmotion.ScrewRDownOutOpen();
                }
                else
                {
                    zmotion.ScrewRDownOutClose();
                }
            }
            else
            {
                AddLog(1, "请检查通信是否连接正常");
            }

        }
        //左吸嘴吸气
        private void btn_Z1Clip_Click(object sender, EventArgs e)
        {
            if (zmotion.connectedOK)
            {
                bool setValue = this.btn_Z1Clip.BackColor != Color.Green;

                if (setValue)
                {
                    zmotion.Z1ClipOpen();
                }
                else
                {
                    zmotion.Z1ClipClose();
                }
            }
            else
            {
                AddLog(1, "请检查通信是否连接正常");
            }
        }

        //左右吸嘴吸气
        private void btn_Z2Clip_Click(object sender, EventArgs e)
        {
            if (zmotion.connectedOK)
            {
                bool setValue = this.btn_Z2Clip.BackColor != Color.Green;

                if (setValue)
                {
                    zmotion.Z2ClipOpen();
                }
                else
                {
                    zmotion.Z2ClipClose();
                }
            }
            else
            {
                AddLog(1, "请检查通信是否连接正常");
            }
        }
        #endregion

        #region 左气缸顶升
        private void btn_ProductUPLOut_Click(object sender, EventArgs e)
        {
            if (zmotion.connectedOK)
            {
                bool setValue = this.btn_ProductUPLOut.BackColor != Color.Green;

                if (setValue)
                {
                    zmotion.ProductUPLOutOpen();
                }
                else
                {
                    zmotion.ProductUPLOutClose();
                }
            }
            else
            {
                AddLog(1, "请检查通信是否连接正常");
            }

        }
        //右产品气缸顶升
        private void btn_ProductUPROut_Click(object sender, EventArgs e)
        {
            if (zmotion.connectedOK)
            {
                bool setValue = this.btn_ProductUPROut.BackColor != Color.Green;

                if (setValue)
                {
                    zmotion.ProductUPROutOpen();
                }
                else
                {
                    zmotion.ProductUPROutClose();
                }
            }
            else
            {
                AddLog(1, "请检查通信是否连接正常");
            }
        }
        private void btn_ProductClampOut_Click(object sender, EventArgs e)
        {
            if (zmotion.connectedOK)
            {
                bool setValue = this.btn_ProductClampOut.BackColor != Color.Green;

                if (setValue)
                {
                    zmotion.ProductClampOutOpen();
                }
                else
                {
                    zmotion.ProductClampOutClose();
                }
            }
            else
            {
                AddLog(1, "请检查通信是否连接正常");
            }
        }



        #endregion


        #region 添加日志

        /// <summary>
        /// 当前时间
        /// </summary>
        private string CurrentTime
        {
            get { return DateTime.Now.ToString("HH:mm:ss"); }
        }

        /// <summary>
        /// 添加日志信息
        /// </summary>
        /// <param name="index">日志等级</param>
        /// <param name="log">日志信息</param>
        public void AddLog(int index, string log)
        {
            if (!this.lst_Info.InvokeRequired)
            {
                ListViewItem lst = new ListViewItem("   " + CurrentTime, index);
                lst.SubItems.Add(log);
                this.lst_Info.Items.Add(lst);
                this.lst_Info.Items[this.lst_Info.Items.Count - 1].EnsureVisible();
            }
            else
            {
                this.lst_Info.Invoke(new Action<int, string>(AddLog), index, log);
            }
        }

        private Timer updateTimer = new Timer();


        private void UpdateTimer_Tick(object sender, EventArgs e)
        {
            if (zmotion.connectedOK)
            {
                if (zmotion.connectedOK)
                {
                    //this.lbl_ConnectState.BackColor = Color.LimeGreen;

                    bool state = zmotion.GetLightLState();
                    this.btn_LightLOpen.Text = state ? "左光源关闭" : "左光源打开";
                    this.btn_LightLOpen.BackColor = state ? Color.Green : Color.DimGray;

                    state = zmotion.GetLightRState();
                    this.btn_LightROpen.Text = state ? "右光源关闭" : "右光源打开";
                    this.btn_LightROpen.BackColor = state ? Color.Green : Color.DimGray;

                    state = zmotion.GetScrewLDownOutState();
                    this.btn_ScrewLDownOut.Text = !state ? "左螺丝刀下降" : "左螺丝刀上升";
                    this.btn_ScrewLDownOut.BackColor = state ? Color.Green : Color.DimGray;

                    state = zmotion.GetScrewRDownOutState();
                    this.btn_ScrewRDownOut.Text = !state ? "右螺丝刀下降" : "右螺丝刀上升";
                    this.btn_ScrewRDownOut.BackColor = state ? Color.Green : Color.DimGray;

                    state = zmotion.Z1ClipState();
                    this.btn_Z1Clip.Text = state ? "左吸嘴吸气" : "左吸嘴松开";
                    this.btn_Z1Clip.BackColor = state ? Color.Green : Color.DimGray;

                    state = zmotion.Z2ClipState();
                    this.btn_Z2Clip.Text = state ? "右吸嘴吸气" : "右吸嘴松开";
                    this.btn_Z2Clip.BackColor = state ? Color.Green : Color.DimGray;


                    state = zmotion.GetProductUPLOutState();
                    this.btn_ProductUPLOut.Text = state ? "左产品下降" : "左产品上升";
                    this.btn_ProductUPLOut.BackColor = state ? Color.Green : Color.DimGray;

                    state = zmotion.GetProductUPROutState();
                    this.btn_ProductUPROut.Text = state ? "右产品下降" : "右产品上升";
                    this.btn_ProductUPROut.BackColor = state ? Color.Green : Color.DimGray;

                    //ProductClampOut
                    state = zmotion.GetProductClampOutState();
                    this.btn_ProductClampOut.Text = state ? "产品顶紧" : "产品松开";
                    this.btn_ProductClampOut.BackColor = state ? Color.Green : Color.DimGray;


                    //state = zmotion.GetXAxisEnable();
                    //this.btn_ProductUPLOut.Text = state ? "X轴使能" : "X轴未使能";
                    //this.btn_ProductUPLOut.BackColor = state ? Color.Green : Color.DimGray;

                    //state = zmotion.GetYAxisEnable();
                    //this.btn_ProductUPROut.Text = state ? "Y轴使能" : "Y轴未使能";
                    //this.btn_ProductUPROut.BackColor = state ? Color.Green : Color.DimGray;

                    //btn_ProductUPLOut

                    this.btn_Z1Right.BackColor = zmotion.GetXLimitPos() ? Color.LimeGreen : Color.FromArgb(2, 69, 163);
                    this.btn_Z1Left.BackColor = zmotion.GetXLimitNeg() ? Color.LimeGreen : Color.FromArgb(2, 69, 163);
                    this.btn_U1Down.BackColor = zmotion.GetYLimitPos() ? Color.LimeGreen : Color.FromArgb(2, 69, 163);
                    this.btn_U1Up.BackColor = zmotion.GetYLimitNeg() ? Color.LimeGreen : Color.FromArgb(2, 69, 163);
                    this.btn_YBackward.BackColor = zmotion.GetZ1LimitPos() ? Color.LimeGreen : Color.FromArgb(2, 69, 163);
                    this.btn_YForward.BackColor = zmotion.GetZ1LimitNeg() ? Color.LimeGreen : Color.FromArgb(2, 69, 163);
                    this.btn_U2Down.BackColor = zmotion.GetZ2LimitPos() ? Color.LimeGreen : Color.FromArgb(2, 69, 163);
                    this.btn_U2Up.BackColor = zmotion.GetZ2LimitNeg() ? Color.LimeGreen : Color.FromArgb(2, 69, 163);
                }
                else
                {
                    //this.lbl_ConnectState.BackColor = Color.Red;
                }

            }
        }

        #endregion

        
    }
}
